import { Injectable } from '@angular/core'
import {
  HandleError,
  HttpErrorHandler,
} from './http-error-handler.service'
import { HttpClient } from '@angular/common/http'

import { catchError, tap, retry, mergeMap, finalize } from 'rxjs/operators'
import { throwError, Observable } from 'rxjs'
import { formatDate } from '@angular/common'
import { Router } from '@angular/router'
import { BASE_URL } from '../config/global-const'
import { NzMessageService } from 'ng-zorro-antd';

@Injectable()
export class HttpsApiService {
  private handleError: HandleError
  constructor(
    private router: Router,
    private http: HttpClient,
    private messageService: NzMessageService,
    private httpErrorHandler: HttpErrorHandler // private utils: UtilService
  ) {
    this.handleError = this.httpErrorHandler.handleError
  }

  // 公共请求
  post(url: string, params: any, callback?: Function) {
    return this.http.post(url, params).pipe(
      catchError(this.handleError()),
      finalize(() => {
        callback && callback()
      })
      // retry(2)
    )
  }

  postTap(url: string, params: any, success: string, callback?: Function) {
    return this.http.post(url, params).pipe(
      catchError(this.handleError()), // retry(2),
      tap((rsp) => this.messageService.success(success)),
      finalize(() => {
        callback && callback()
      }) // retry(2)
    )
  }

  // 删除/添加/修改  提示接口
  postAdd(url: string, params: any, callback?: Function) {
    return this.http.post(url, params)
  }

  // 传json
  get(url: string, json?: any) {
    json =
      json && Object.keys(json).length
        ? '?' +
        Object.keys(json)
          .map((key) => {
            return key + '=' + json[key]
            // return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
          })
          .join('&')
        : ''

    return this.http.get(url + json).pipe(
      catchError(this.handleError()),
      // retry(2),
      mergeMap((data) => {
        console.log(data)
        return data['code'] === '0000' || data['status'] === '0'
          ? this.httpErrorHandler.errorCode(data['code'])
          : throwError('返回值错误')
      })
    )
  }

  // 传json
  getExport(url: string, name: string, json?: any, isXls?: boolean) {
    json =
      json && Object.keys(json).length
        ? '?' +
        Object.keys(json)
          .map((key) => {
            return (
              key +
              '=' +
              (json[key] === null || json[key] === undefined ? '' : json[key])
            )
            // return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
          })
          .join('&')
        : ''
    // 获取XMLHttpRequest
    let xmlResquest = new XMLHttpRequest()
    //  发起请求
    xmlResquest.open('post', url + json, true)
    // 设置请求头类型
    xmlResquest.setRequestHeader('Content-type', 'application/json')
    xmlResquest.responseType = 'blob'
    //  返回
    xmlResquest.onload = (oEvent) => {
      let content = xmlResquest.response
      // 组装a标签
      let elink = document.createElement('a')
      // 设置下载文件名
      elink.download =
        name +
        formatDate(new Date(), 'yyyy-MM-dd', 'zh') +
        (isXls ? '.xls' : '.xlsx')

      // name + this.utils.format(new Date()) + (isXls ? '.xls' : '.xlsx')
      elink.style.display = 'none'
      let blob = new Blob([content])
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
    xmlResquest.send()
  }
  // 传json
  getExportr(url: string, name: string, json?: any, isXls?: boolean) {
    json =
      json && Object.keys(json).length
        ? '?' +
        Object.keys(json)
          .map((key) => {
            return (
              key +
              '=' +
              (json[key] === null || json[key] === undefined ? '' : json[key])
            )
            // return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
          })
          .join('&')
        : ''
    // 获取XMLHttpRequest
    let xmlResquest = new XMLHttpRequest()
    //  发起请求
    xmlResquest.open('post', url + json, true)
    // 设置请求头类型
    xmlResquest.setRequestHeader('Content-type', 'application/json')
    xmlResquest.responseType = 'blob'
    //  返回
    xmlResquest.onload = (oEvent) => {
      let content = xmlResquest.response
      // 组装a标签
      let elink = document.createElement('a')
      // 设置下载文件名
      elink.download = name + (isXls ? '.xls' : '.xlsx')

      // name + this.utils.format(new Date()) + (isXls ? '.xls' : '.xlsx')
      elink.style.display = 'none'
      let blob = new Blob([content])
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
    xmlResquest.send()
  }
  getExports(url: string, name: string, json?: any, isXls?: boolean) {
    json =
      json && Object.keys(json).length
        ? '?' +
        Object.keys(json)
          .map((key) => {
            return (
              key +
              '=' +
              (json[key] === null || json[key] === undefined ? '' : json[key])
            )
            // return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
          })
          .join('&')
        : ''
    // 获取XMLHttpRequest
    let xmlResquest = new XMLHttpRequest()
    //  发起请求
    xmlResquest.open('post', url + json, true)
    // 设置请求头类型
    xmlResquest.setRequestHeader('Content-type', 'application/json')
    xmlResquest.responseType = 'blob'
    //  返回
    xmlResquest.onload = (oEvent) => {
      let content = xmlResquest.response
      // 组装a标签
      let elink = document.createElement('a')
      // 设置下载文件名
      elink.download =
        name +
        formatDate(new Date(), 'yyyy-MM-dd', 'zh') +
        (isXls ? '.zip' : '.xlsx')

      // name + this.utils.format(new Date()) + (isXls ? '.xls' : '.xlsx')
      elink.style.display = 'none'
      let blob = new Blob([content])
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
    xmlResquest.send()
  }
  // 传json
  getExportDocx(url: string, name: string, json?: any, isXls?: boolean) {
    json =
      json && Object.keys(json).length
        ? '?' +
        Object.keys(json)
          .map((key) => {
            return (
              key +
              '=' +
              (json[key] === null || json[key] === undefined ? '' : json[key])
            )
            // return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
          })
          .join('&')
        : ''
    // 获取XMLHttpRequest
    let xmlResquest = new XMLHttpRequest()
    //  发起请求
    xmlResquest.open('post', url + json, true)
    // 设置请求头类型
    xmlResquest.setRequestHeader('Content-type', 'application/json')
    xmlResquest.responseType = 'blob'
    //  返回
    xmlResquest.onload = (oEvent) => {
      let content = xmlResquest.response
      // 组装a标签
      let elink = document.createElement('a')
      // 设置下载文件名
      elink.download =
        name +
        formatDate(new Date(), 'yyyy-MM-dd', 'zh') +
        (isXls ? '.docx' : '.doc')

      // name + this.utils.format(new Date()) + (isXls ? '.xls' : '.xlsx')
      elink.style.display = 'none'
      let blob = new Blob([content])
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
    }
    xmlResquest.send()
  }
}
